const app = getApp()
const {
  envList
} = require('../../../envList.js');
var util = require('../../../utils/util.js');
Page({
  data: {
    envList,
    selectedEnv: envList[0],
    custom: false,
    TabCur: 0,
    scrollLeft: 0,
    tabList: ['发布商品', '商品仓库'],
    goods_list: [],
    goods_length: 0,
    limit: 5,
    skip: 0,
    imgList: [],
    cardCur: 0,
    cardList: [{
      id: 1,
      type: 'image',
      url: 'https://i0.hdslb.com/bfs/album/65964c7ae72edd111de12958651ecf8ecb735e2c.jpg'
    }, {
      id: 2,
      type: 'image',
      url: 'https://i0.hdslb.com/bfs/album/4685705292b813983819e409032e2e1dec2d14c2.jpg'
    }, {
      id: 3,
      type: 'image',
      url: 'https://i0.hdslb.com/bfs/album/afd1055615b4597fe4cc2d91fc3890c94d272025.jpg'
    }]
  },
  onLoad: function (options) {
    this.setData({
      goods_url: this.data.cardList[0].url
    })
  },
  // 卡片切换
  cardSwiper(e) {
    this.setData({
      cardCur: e.detail.current,
      goods_url: this.data.cardList[e.detail.current].url
    })
  },
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    });
    if (e.currentTarget.dataset.id == 1) {
      this.tabGetGoods();
    }
  },
  tabGetGoods() {
    if (util.get('goods_list', 'outTime') == 'outTime') {
      this.setData({
        limit: 5,
        skip: 0,
        goods_list: []
      });
      this.getGoodsList(this.data.limit, this.data.skip);
    } else {
      console.log('【商品仓库】页面数据调用缓存。');
      wx.hideLoading();
      this.setData({
        goods_list: wx.getStorageSync('goods_list'),
        goods_length: wx.getStorageSync('goods_length'),
      })
    }
  },
  // 获取商品列表
  getGoodsList(limit, skip) {
    var that = this;
    let times = 120;
    wx.showLoading({
      title: '系统正在处理',
    })
    wx.cloud.callFunction({
      name: "getGoodsList",
      data: {
        limit: limit,
        skip: skip
      },
      success: res => {
        wx.hideLoading();
        // console.log(res);
        if (res.result.goods_length == 0) {
          that.setData({
            goods_list: []
          });
        } else {
          that.setData({
            limit: limit,
            goods_length: res.result.goods_length,
            goods_list: that.data.goods_list.concat(res.result.goods_list)
          });
          // 缓存times秒
          if (that.data.goods_length == that.data.goods_list.length) {
            util.put('goods_list', that.data.goods_list, times);
            util.put('goods_length', that.data.goods_length, times);
          }
        }
      }
    })
  },
  // 选择图片
  ChooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {

          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths),
          })
        } else {
          let path = res.tempFilePaths[0];
          // console.log('path:' + path);
          this.setData({
            imgList: res.tempFilePaths,
            // 文件转码为base64
            fileContent: wx.getFileSystemManager().readFileSync(path, 'base64')
          })
        }
      }
    });
  },
  // 删除商品
  delGoods(e) {
    wx.showModal({
      title: '删除商品',
      content: '确认删除 ' + e.currentTarget.dataset.name + ' ？',
      confirmColor: '#10c55b',
      success: res => {
        if (res.confirm) {
          wx.showLoading({
            title: '系统正在处理',
          });
          wx.cloud.callFunction({
            name: "deleteGoods",
            data: {
              goods_id: e.currentTarget.dataset.id
            },
            success: res => {
              wx.hideLoading();
              // console.log(res);
              if (res.result.stats.updated == 1) {
                wx.removeStorageSync('goods_list');
                wx.removeStorageSync('goods_length');
                this.tabGetGoods();
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
              } else {
                wx.showToast({
                  title: '删除失败',
                  icon: 'error'
                })
              }
            }
          })
        }
      }
    })
  },
  // 预览图片
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除该图片吗？',
      confirmColor: '#10c55b',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  // 发布商品
  formSubmit(e) {
    if (e.detail.value.goods_name.length != 0 && e.detail.value.specs.length != 0 && e.detail.value.type.length != 0 && e.detail.value.goods_explain.length != 0 ) {
      if(this.data.custom == true && this.data.imgList.length == 0){
        wx.showToast({
          title: '请上传图片',
          icon: 'error'
        })
      }else{
        this.setData({
          btn_disabled: 'disabled'
        });
        wx.showLoading({
          title: '系统正在处理',
        })
        wx.cloud.callFunction({
          name: "addGoods",
          data: {
            goods_name: e.detail.value.goods_name,
            specs: e.detail.value.specs,
            type: e.detail.value.type,
            goods_explain: e.detail.value.goods_explain,
            fileContent: this.data.fileContent,
            custom: this.data.custom,
            goods_url: this.data.goods_url
          },
          success: res => {
            wx.hideLoading();
            this.setData({
              btn_disabled: ''
            });
            if (res.result._id.length != 0) {
              wx.showModal({
                title: '发布成功',
                content: '是否继续发布商品？',
                confirmColor: '#10c55b',
                confirmText: '继续发布',
                cancelText: '商品仓库',
                success: res => {
                  if (res.cancel) {
                    wx.removeStorageSync('goods_list');
                    wx.removeStorageSync('goods_length');
                    this.setData({
                      TabCur: 1
                    });
                    this.tabGetGoods();
                  }
                }
              })
            } else {
              wx.showModal({
                title: '发布失败',
                content: '是否重新发布商品？',
                confirmColor: '#10c55b',
                confirmText: '重新发布'
              });
            }
          }
        })
      }
    } else {
      wx.showToast({
        title: '参数不能为空',
        icon: 'error'
      }, 2000)
    }

  },
  // 上拉触底，获取签发记录
  onReachBottom() {
    if (this.data.TabCur == 1) {
      console.log('上拉触底');
      if (this.data.goods_list.length < this.data.goods_length) {
        this.getGoodsList(this.data.limit + 5, this.data.skip + this.data.limit);
      } else {
        wx.showToast({
          title: '数据加载完毕',
          icon: 'success',
        })
      }
    }
  },
  // 自定义图片
  changeCustom(e) {
    this.setData({
      custom: !e.currentTarget.dataset.custom
    })
  },
  // 预览图片
  downloadImage(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.url] // 需要预览的图片http链接列表
    })
  }
})